#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"data_ops.h"
#include<string.h>
#include<glib.h>
#include<unistd.h>


//初始化数据文件目录
void init_data_dir(){
	//打印当前初始化目录路径
	g_print("初始化目录路径：/home/yangchun/pingpong_system/pingpong_member\n");

	//创建目录，检查是否成功
	int mkdir_result = system("mkdir -p /home/yangchun/pingpong_system/pingpong_member");
	if(mkdir_result != 0){
		g_print("错误");
		return;
	}

	const char *files[] = {MEMBER_FILE, ADMIN_FILE, RECORD_FILE};
	for(int i = 0; i < 3; i++){
		FILE *f = fopen(files[i], "a+");
		if(f){
			g_print("成功打开：%s\n", files[i]);
			fclose(f);
		}else{
			g_print("错误：无法创建%s\n", files[i]);
		}
	}
}

//获取当前时间
void get_current_time(char *time_str, int format){
	time_t t = time(NULL);
	struct tm *tm = localtime(&t);
	if(format == 0){
			strftime(time_str, 20, "%Y-%m-%d %H:%M:%S", tm);
	}else{
		strftime(time_str, 11, "%Y-%m-%d", tm);
	}
}

//添加会员
int add_member(Member *member){
	init_data_dir();

	FILE *f = fopen(MEMBER_FILE, "rb");
	if(f){
		Member temp;
		while(fread(&temp, sizeof(Member), 1, f) == 1){
			if(strcmp(temp.card_id, member->card_id) == 0){
				fclose(f);
				return -2;//卡号已经存在
			}
		}
		fclose(f);
	}

	get_current_time(member->register_date, 0);

	f = fopen(MEMBER_FILE, "ab");
	if(!f) return -1;

	//写入会员信息
	fwrite(member, sizeof(Member), 1, f);
	fclose(f);
	return 0;
}

//按卡号注销会员（只修改状态）
int deactivate_member_by_card_id(const char *card_id){
    init_data_dir();
    FILE *f = fopen(MEMBER_FILE, "rb");
    FILE *temp = fopen("/tmp/members.tmp", "wb");
    if(!f  || !temp) return -1;    

    Member m;
    int found = 0;
    while(fread(&m, sizeof(Member), 1, f) == 1){
        if (strcmp(m.card_id, card_id) == 0){
            m.status = 1;//标记为注销
            found = 1;
        }
        fwrite(&m, sizeof(Member), 1, temp);
    }
    fclose(f);
    fclose(temp);

    //替换原文件
    remove(MEMBER_FILE);
    rename("/tmp/members.tmp", MEMBER_FILE);

    return found ? 0 : -1;
}

// 更新会员信息
int update_member(Member *member){
    init_data_dir();
    FILE *f = fopen(MEMBER_FILE, "rb");
    if(!f) return -1;
    
    FILE *temp = fopen("/tmp/members.tmp", "wb");
    if(!temp) {
        fclose(f);
        return -1;
    }
    
    Member m;
    int found = 0;
    while(fread(&m, sizeof(Member), 1, f) == 1){
        if(strcmp(m.card_id, member->card_id) == 0){
            // 保留原始注册时间
            strcpy(member->register_date, m.register_date);
            fwrite(member, sizeof(Member), 1, temp);
            found = 1;
        } else {
            fwrite(&m, sizeof(Member), 1, temp);
        }
    }
    
    fclose(f);
    fclose(temp);
    
    if(found) {
        // 替换原文件
        if(remove(MEMBER_FILE) != 0) {
            return -1;
        }
        if(rename("/tmp/members.tmp", MEMBER_FILE) != 0) {
            return -1;
        }
        return 0;
    } else {
        remove("/tmp/members.tmp");
        return -1;
    }
}

//按卡号查找会员
Member *find_member_by_card_id(const char *card_id){
	init_data_dir();
	FILE *f = fopen(MEMBER_FILE, "rb");
	if(!f) return NULL;

	Member *m = malloc(sizeof(Member));
	while(fread(m, sizeof(Member), 1, f) == 1){
		if(strcmp(m->card_id, card_id) == 0){
			fclose(f);
			return m;
		}
	}
	fclose(f);
	free(m);
	return NULL;
}

//按姓名查找会员
Member *find_member_by_name(const char *name, int *count){
	init_data_dir();
	FILE *f = fopen(MEMBER_FILE, "rb");
	if(!f){
		*count = 0;
		return NULL;
	}

	//统计数量
	*count = 0;
	Member temp;
	while(fread(&temp, sizeof(Member), 1, f) == 1){
		if(strstr(temp.name, name) != NULL && temp.status == 0){
			(*count)++;
		}
	}

	if(*count == 0){
		fclose(f);
		return NULL;
	}

	//分配内存并储存结果
	Member *members = malloc(sizeof(Member) * (*count));
	rewind(f);//回到文件开头
	int index = 0;
	while(fread(&temp, sizeof(Member), 1, f) == 1){
		if(strstr(temp.name, name) != NULL && temp.status == 0){
			members[index++] = temp;
		}
	}
	fclose(f);
	return members;
}

//按手机号查找所有会员
Member *find_member_by_phone(const char *phone){
	init_data_dir();
	FILE *f = fopen(MEMBER_FILE, "rb");
	if(!f) return NULL;

	Member *m = malloc(sizeof(Member));
	while(fread(m, sizeof(Member), 1, f) == 1){
		if(strcmp(m->phone, phone) == 0 && m-> status == 0){
			fclose(f);
			return m;
		}
	}
	fclose(f);
	free(m);
	return NULL;

}
//获取所有会员
Member *get_all_members(int *count){
	init_data_dir();
	FILE *f = fopen(MEMBER_FILE, "rb");
	if(!f){
		*count = 0;
		return NULL;
	
	}
	//先统计活跃会员数量
	*count = 0;
	Member temp;
	while(fread(&temp,sizeof(Member), 1, f) == 1){
		if(temp.status == 0){
			(*count)++;
		}
	}

	if(*count == 0){
		fclose(f);
		return NULL;
	}

	//读取活跃会员
	rewind(f);
	Member *members = malloc(sizeof(Member) * (*count));
	int index = 0;
	while(fread(&temp, sizeof(Member), 1, f) == 1){
		if(temp.status == 0){
			members[index++] = temp;
		}
	}
	fclose(f);
	return members;


}

//添加管理员
int add_admin(const char *username, const char *password){
	init_data_dir();
	FILE * f = fopen(ADMIN_FILE, "ab");
	if(!f) return -1;

	Admin admin;
	strcpy(admin.username, username);
	strcpy(admin.password, password);
	fwrite(&admin, sizeof(Admin), 1, f);
	fclose(f);
	return 0;
}
//按卡号获取所有记录
Record *get_records_by_card_id(const char *card_id, int *count){
	init_data_dir();
	FILE *f = fopen(RECORD_FILE, "rb");
	if(!f){
		*count = 0;
		return NULL;
	}

	//统计匹配记录数
	*count = 0;
	Record temp;
	while(fread(&temp, sizeof(Record), 1, f) == 1){
		if(strcmp(temp.card_id, card_id) == 0){
			(*count)++;
		}
	}
	if(*count == 0){
		fclose(f);
		return NULL;
	}

	//读取匹配记录
	Record *records = malloc(sizeof(Record) * (*count));
	rewind(f);
	int index = 0;
	while(fread(&temp, sizeof(Record), 1, f) == 1){
		if(strcmp(temp.card_id, card_id) == 0){
			records[index++] = temp;
		}
	}
	fclose(f);
	return records;

}
//获取所有记录
Record *get_all_records(int *count){
	init_data_dir();
	FILE *f = fopen(RECORD_FILE, "rb");
	if(!f){
		*count = 0;
		return NULL;
	}
	
	//统计总数量
	fseek(f, 0, SEEK_END);
	*count = ftell(f) / sizeof(Record);
	rewind(f);

	if(*count == 0){
		fclose(f);
		return NULL;
	}

	//读取所有记录
	Record *records = malloc(sizeof(Record) * (*count));
	fread(records, sizeof(Record), *count, f);
	fclose(f);

	return records;
	
}
// 管理员登录验证
int admin_login(const char *username, const char *password){
    init_data_dir();
    FILE *f = fopen(ADMIN_FILE, "rb");
    if(!f) return 0;

    Admin a;
    // 直接比对明文密码，不进行加密
    while(fread(&a, sizeof(Admin), 1, f) == 1){
        if(strcmp(a.username, username) == 0 && 
           strcmp(a.password, password) == 0){  // 直接比较明文
            fclose(f);
            return 1;  // 验证成功
        }
    }
    fclose(f);
    return 0;  // 验证失败
}

//添加入场/离场记录
int add_record(const char *card_id, int is_entry){
	init_data_dir();
	FILE *f = fopen(RECORD_FILE, "rb+");
	if(!f){
		f = fopen(RECORD_FILE, "wb");
		if(!f) return -1;
	}

	Record r;
	char time_str[20];
	get_current_time(time_str, 0);

	if(is_entry){
		//入场记录
		strcpy(r.card_id, card_id);
		strcpy(r.in_time, time_str);
		r.out_time[0] = '\0';
		fseek(f, 0, SEEK_END);
		fwrite(&r, sizeof(Record), 1, f);
	}else{
		//离场记录
		int found = 0;
		long pos = 0;

		while(fread(&r, sizeof(Record), 1, f) == 1){
			if(strcmp(r.card_id, card_id) == 0 && r.out_time[0] == '\0'){
					pos = ftell(f) - sizeof(Record);
					found = 1;
			}
		}
		if(found){
			fseek(f, pos, SEEK_SET);
			strcpy(r.out_time, time_str);
			fwrite(&r, sizeof(Record), 1, f);
		}else{
			fclose(f);
			return -1;
		}
	}
	fclose(f);
	return 0;
}

// 将会员类型枚举转换为字符串
const char* card_type_to_string(CardType type) {
    switch(type) {
        case CARD_TYPE_TIMES: return "次卡";
        case CARD_TYPE_MONTH: return "月卡";
        case CARD_TYPE_QUARTER: return "季卡";
        case CARD_TYPE_YEAR: return "年卡";
        default: return "未知类型";
    }
}

// 将字符串转换为会员类型枚举
CardType string_to_card_type(const char* str) {
    if(strcmp(str, "次卡") == 0) return CARD_TYPE_TIMES;
    if(strcmp(str, "月卡") == 0) return CARD_TYPE_MONTH;
    if(strcmp(str, "季卡") == 0) return CARD_TYPE_QUARTER;
    if(strcmp(str, "年卡") == 0) return CARD_TYPE_YEAR;
    return CARD_TYPE_TIMES; // 默认次卡
}
